import { throttle } from '@/utils/common';
import { useEffect, useLayoutEffect, useState } from 'react';

export function useWindowWidth(delayMs = 100) {
  const [width, setWidth] = useState(1200);

  // 监听窗口大小变化
  useLayoutEffect(() => {
    const _resizeHandler = () => {
      setWidth(document.documentElement.clientWidth);
    };
    const resizeHandler = throttle(_resizeHandler, delayMs / 1000);
    window.addEventListener('resize', resizeHandler);
    _resizeHandler();

    return () => {
      window.removeEventListener('resize', resizeHandler);
    };
  }, [delayMs]);

  return width;
}
